<template>
  <div class="qr-scanner">
    <el-dialog
        v-model="dialogVisible"
        title="扫码签到"
        width="500px"
        @closed="handleClose"
    >
      <div class="scanner-container">
        <div id="qr-reader" style="width: 100%"></div>
        <div v-if="decodedData" class="decoded-info">
          <h3>扫描结果:</h3>
          <p>{{ decodedData }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onUnmounted } from 'vue';
import { ElDialog, ElMessage } from 'element-plus';

export default {
  components: {
    ElDialog
  },
  setup(props, { emit }) {
    const dialogVisible = ref(false);
    const decodedData = ref(null);
    let html5QrCode = null;

    const openScanPage = () => {
      dialogVisible.value = true;
      // 延迟初始化扫描器，确保DOM已经渲染
      setTimeout(() => {
        initScanner();
      }, 100);
    };

    const initScanner = async () => {
      try {
        // 动态导入html5-qrcode库
        const { Html5Qrcode } = await import('html5-qrcode');
        
        // 创建扫描器实例
        html5QrCode = new Html5Qrcode("qr-reader");
        
        const config = { fps: 10, qrbox: { width: 250, height: 250 } };
        
        // 开始扫描
        html5QrCode.start(
          { facingMode: "environment" }, // 使用后置摄像头
          config,
          onScanSuccess,
          onScanFailure
        ).catch(error => {
          handleScanError(error);
        });
      } catch (error) {
        ElMessage.error('初始化扫描器失败');
        console.error('初始化扫描器失败:', error);
      }
    };

    const onScanSuccess = (decodedText) => {
      decodedData.value = decodedText;
      emit('onScanSuccess', decodedText);
      
      // 停止扫描
      if (html5QrCode) {
        html5QrCode.stop().then(() => {
          ElMessage.success('扫描成功');
        }).catch(error => {
          console.error('停止扫描失败:', error);
        });
      }
      
      // 延迟关闭对话框
      setTimeout(() => {
        stopScan();
      }, 2000);
    };

    const onScanFailure = (error) => {
      // 扫描失败时不需要显示错误，这是正常的过程
      console.log('扫描中...', error);
    };

    const handleScanError = (error) => {
      if (error.name === 'NotAllowedError') {
        ElMessage.error('请求摄像头权限失败，请允许使用摄像头');
      } else if (error.name === 'NotFoundError') {
        ElMessage.error('未找到摄像头设备');
      } else if (error.name === 'NotSupportedError') {
        ElMessage.error('您的环境不支持此功能');
      } else if (error.name === 'NotReadableError') {
        ElMessage.error('摄像头正在被其他应用使用');
      } else {
        ElMessage.error('初始化摄像头失败: ' + error.message);
      }
    };

    const stopScan = () => {
      dialogVisible.value = false;
      if (html5QrCode && html5QrCode.isScanning) {
        html5QrCode.stop().catch(error => {
          console.error('停止扫描失败:', error);
        });
      }
    };

    const handleClose = () => {
      decodedData.value = null;
      if (html5QrCode && html5QrCode.isScanning) {
        html5QrCode.stop().catch(error => {
          console.error('停止扫描失败:', error);
        });
      }
    };

    onUnmounted(() => {
      if (html5QrCode && html5QrCode.isScanning) {
        html5QrCode.stop().catch(error => {
          console.error('停止扫描失败:', error);
        });
      }
    });

    return {
      dialogVisible,
      decodedData,
      openScanPage,
      stopScan,
      handleClose
    };
  }
};
</script>

<style>
.scanner-container {
  position: relative;
  margin-bottom: 20px;
}

.decoded-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

#qr-reader {
  width: 100%;
  margin: 0 auto;
}

#qr-reader video {
  width: 100%;
  height: auto;
}

#qr-reader__scan_region {
  position: relative;
}

#qr-reader__dashboard {
  padding: 10px;
}
</style>



